<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use think\facade\Env;
use think\helper\Str;
use app\model\Bazaar;
use OSS\OssClient;
use OSS\Core\OssException;
use \wapmorgan\UnifiedArchive\UnifiedArchive;

class Templates extends Common
{

	/**
	 * 上传图片
	 *
	 * @return
	 */
	public function imageUpload(Request $request)
	{
		$files = $request->file();
		if (!isset($files['file'])) {
			return json(['code'=> 403, 'msg'=> '上传失败!']);
		}
		if(!is_object($files['file'])) {
			return json(['code'=> 403, 'msg'=> '上传失败!']);
		}
		$object = 'templates' . '/'. sha1( $request->sessInfo['companyId'] . microtime(true)) . '.' . $files['file']->getOriginalExtension();
		$array = $this->imageUploadFile($object, $files['file']->getPathName(), $files['file']->getOriginalName());
		return json($array);
	}

	/**
	 * 上传方法
	 *
	 * @return
	 */
	protected function imageUploadFile($object, $filePath, $fileName)	{
		$result = ['code'=> 403, 'msg'=> '上传失败!'];
		if (file_exists($filePath) == false) {
			return $result;
		}
		$bucket = Env::get('aliyun.bucket', 'bucket');
		if ($bucket == 'bucket') {
			return $result;
		}
		$endpoint = Env::get('aliyun.endpoint', 'endpoint');
		if ($endpoint == 'endpoint') {
			return $result;
		}
		$accessKeyId = Env::get('aliyun.accesskeyid', 'accesskeyid');
		if ($accessKeyId == 'accessKeyId') {
			return $result;
		}
		$accessKeySecret = Env::get('aliyun.accesskeysecret', 'accesskeysecret');
		if ($accessKeySecret == 'accessKeySecret') {
			return $result;
		}
		$originaldomain = Env::get('aliyun.originaldomain', 'originaldomain');
		if ($originaldomain == 'originaldomain') {
			return $result;
		}
		$domain = Env::get('aliyun.domain', 'domain');
		if ($domain == 'domain') {
			return $result;
		}
		try {
			$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$result = $ossClient->uploadFile($bucket, $object, $filePath);
			if (isset($result['info']['http_code']) && $result['info']['http_code'] == 200) {
				$result = ['code'=> 0, 'msg'=> $fileName, 'url' => str_replace($originaldomain, $domain, $result['info']['url'])];
			}
		} catch (OssException $e) {
			$result = ['code'=> 403, 'msg'=>$e->getMessage()];
		}
		return $result;
	}

	/**
	 * 上传源码
	 *
	 * @return
	 */
	public function zipUpload(Request $request)
	{
		$files = $request->file();
		if (!isset($files['file'])) {
			return json(['code'=> 403, 'msg'=> '上传失败!']);
		}
		if(!is_object($files['file'])) {
			return json(['code'=> 403, 'msg'=> '上传失败!']);
		}
		$archive = UnifiedArchive::open($files['file']->getPathName());
		if(!is_object($archive)) {
			return json(['code'=> 403, 'msg'=> '上传失败, 权限不足!']);
		}
		if ($archive->isFileExists('index.html') === false ) {
			return json(['code'=> 403, 'msg'=> '上传失败, 没有检测到index.html文件!' ]);
		}
		$content = $archive->getFileContent('index.html');
		if( stripos($content, '</head>') === false ) {
			return json(['code'=> 403, 'msg'=> "上传失败, 没有检测到&lt;/head&gt;标签!" ]);
		}
		$content = $archive->getFileContent('index.html');
		if( stripos($content, '</body>') === false ) {
			return json(['code'=> 403, 'msg'=> "上传失败, 没有检测到&lt;/body&gt;标签!" ]);
		}
		if( stripos($content, 'san_cloud.js') !== false ) {
			return json(['code'=> 403, 'msg'=> '上传失败, 请先去掉客服统计代码!' ]);
		}
		if( stripos($content, 'cnzz.com') !== false ) {
			return json(['code'=> 403, 'msg'=> '上传失败, 请先去掉CNZZ统计代码!' ]);
		}
		if( stripos($content, 'hm.baidu.com') !== false ) {
			return json(['code'=> 403, 'msg'=> '上传失败, 请先去掉百度统计代码!' ]);
		}
    try {
			validate([
				'file' => [
					'fileSize' => 15728640,
					'fileExt' => 'zip',
				]
			])->check($files);
			$fileName = hash_file('sha1', $files['file']->getPathName());
			$savename = \think\facade\Filesystem::disk('public')->putFileAs( 'templates', $files['file'], $fileName);
			if($savename){
				return json(['code'=> 0, 'msg'=> '源码上传成功!', 'url' => $fileName ]);
			}
    } catch (\think\exception\ValidateException $e) {
			return json(['code'=> 403, 'msg'=> $e->getMessage()]);
    }
		return json(['code'=> 403, 'msg'=> '上传失败!']);
		//$object = 'templates' . '/'. sha1( $request->sessInfo['companyId'] . microtime(true) ) . '.' . $files['file']->getOriginalExtension();
		//$array = $this->zipUploadFile($object, $files['file']->getPathName());
		//return json($array);
	}

	/**
	 * 上传方法
	 *
	 * @return
	 */
	protected function zipUploadFile($object, $filePath)	{
		$result = ['code'=> 403, 'msg'=> '上传失败!'];
		if (file_exists($filePath) == false) {
			return $result;
		}
		$bucket = Env::get('aliyun.bucket', 'bucket');
		if ($bucket == 'bucket') {
			return $result;
		}
		$endpoint = Env::get('aliyun.endpoint', 'endpoint');
		if ($endpoint == 'endpoint') {
			return $result;
		}
		$accessKeyId = Env::get('aliyun.accesskeyid', 'accesskeyid');
		if ($accessKeyId == 'accessKeyId') {
			return $result;
		}
		$accessKeySecret = Env::get('aliyun.accesskeysecret', 'accesskeysecret');
		if ($accessKeySecret == 'accessKeySecret') {
			return $result;
		}
		$originaldomain = Env::get('aliyun.originaldomain', 'originaldomain');
		if ($originaldomain == 'originaldomain') {
			return $result;
		}
		$domain = Env::get('aliyun.domain', 'domain');
		if ($domain == 'domain') {
			return $result;
		}
		$archive = UnifiedArchive::open($filePath);
		if(!is_object($archive)) {
			return json(['code'=> 403, 'msg'=> '上传失败, 权限不足!']);
		}

		if ($archive->isFileExists('index.html') === false ) {
			return ['code'=> 403, 'msg'=> '上传失败, 没有检测到index.html文件!' ] ;
		}

		$body = $archive->getFileContent('index.html');
		if( stripos($body, '</head>') === false ) {
			return ['code'=> 403, 'msg'=> "上传失败, 没有检测到&lt;/head&gt;标签!" ];
		}

		if( stripos($body, 'san_cloud.js') !== false ) {
			return ['code'=> 403, 'msg'=> '上传失败, 请先去掉客服统计代码!' ];
		}

		if( stripos($body, 'cnzz.com') !== false ) {
			return ['code'=> 403, 'msg'=> '上传失败, 请先去掉CNZZ统计代码!' ];
		}

		if( stripos($body, 'hm.baidu.com') !== false ) {
			return ['code'=> 403, 'msg'=> '上传失败, 请先去掉百度统计代码!' ];
		}

		try {
			$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$result = $ossClient->uploadFile($bucket, $object, $filePath);
			if (isset($result['info']['http_code']) && $result['info']['http_code'] == 200) {
				$result = ['code'=> 0, 'msg'=> '源码上传成功!', 'url' => str_replace($originaldomain, $domain, $result['info']['url'])];
			}
		} catch (OssException $e) {
			$result = ['code'=> 403, 'msg'=>$e->getMessage()];
		}
		return $result;
	}

	/**
	 * 创建数据
	 *
	 * @return
	 */
	public function create(Request $request) {
		$image = $request->param('image', '', 'trim');
		$name = $request->param('name', '', 'trim');
		$remark = $request->param('remark', '', 'trim');
		$sort = $request->param('sort', '', 'trim');
		$source = $request->param('source', '', 'trim');
		$status = $request->param('status', '', 'trim');
		if(empty($name)) {
			return ['code'=>403, 'msg'=>'模板名称不能为空!'];
		}
		Db::name('cfg_templates')->insert([ 'image' => $image, 'name' => $name, 'remark' => $remark, 'sort' => $sort, 'source' => $source,
		'status' => $status, 'datetime' => date('Y-m-d H:i:s') ]);
		return ['code'=>0, 'msg'=>'操作成功'];
	}

	/**
	 * 查询数据
	 *
	 * @return
	 */
	public function read(Request $request) {
		$where = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');
		$name = $request->param('name', '', 'trim');
		if($name) {
			array_push( $where, ['name', 'like',  "%{$name}%" ] );
		}
		$query = Db::name('cfg_templates')->where($where)->order($sort, $order)->paginate($limit);
		$items = $query->items();
		foreach($items as &$value ) {
			if($value['source']) {
				$value['issource'] = file_exists(public_path('storage')  . 'templates' . DIRECTORY_SEPARATOR . $value['source']);
			} else {
				$value['issource'] = false;
			}
			$value['image'] = json_decode($value['image']);
		}
		return ['code'=> 0, 'msg'=> '', 'count'=> $query->total(), 'data'=> $items ];
	}

	/**
	 * 删除数据
	 *
	 * @return
	 */
	public function delete(Request $request) {
		$param = $request->param();
		if( !isset($param['id']) ) {
			return ['code'=> 403, 'msg'=> '操作失败!'];
		}
		$beginTime = microtime(true);
		$delTemp = [];
		$explode = explode(',', $param['id']);
		foreach( $explode as $value ) {
			array_push($delTemp, Db::table('cfg_templates')->where('id', $value)->value('name'));
			Db::table('cfg_templates')->where('id', $value)->delete();
		}
		unset($explode, $value);
		foreach( $delTemp as $value ) {
			if( $value ) {
				$endTime = microtime(true);
				$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
				$request->sessInfo['username'], round($endTime - $beginTime, 3), '落地页管理', '删除模板['.$value.']', 0, json_encode($param));
			}
		}
		unset($delTemp, $value);
		return ['code'=> 0, 'msg'=> '删除成功!'];
	}

	/**
	 * 编辑数据
	 *
	 * @return
	 */
	public function edit(Request $request) {
		$id = $request->param('id', '', 'trim');
		$image = $request->param('image', '', 'trim');
		$name = $request->param('name', '', 'trim');
		$remark = $request->param('remark', '', 'trim');
		$sort = $request->param('sort', '', 'trim');
		$source = $request->param('source', '', 'trim');
		$status = $request->param('status', '', 'trim');
		if(empty($name)) {
			return ['code'=>403, 'msg'=>'模板名称不能为空!'];
		}
		Db::name('cfg_templates')->where('id', $id)
				->update([ 'image' => $image, 'name' => $name, 'remark' => $remark, 'sort' => $sort, 'source' => $source,'status' => $status]);
		return json(['code'=>0, 'msg'=>'操作成功']);
	}

	/**
	 * 更新数据
	 *
	 * @return
	 */
	public function update(Request $request) {
		$param = $request->param();
		Db::name('cfg_templates')->where('id', $param['state'])->update([ 'status' => $param['status']]);
		return ['code'=>0, 'msg'=>'操作成功'];
	}
}
